<template>
  <div class="flex justify-center items-center h-screen bg-gray-100">
    <div class="bg-white rounded-lg shadow-lg p-8 w-96 h-100 bg-opacity-80">
      <div class="text-center text-2xl font-bold mb-4 text-gray-800">
        <span class="text-black-700">Login</span>
      </div>
      <a-form ref="formRef" :model="formState" :rules="rules" @finish="handleLogin">
        <a-form-item name="userId">
          <label for="userId" class="block text-gray-700 font-medium mb-1">学号</label>
          <div class="relative">
            <img
              src="@/assets/person.png"
              alt="User Icon"
              class="absolute left-3 top-[50%] transform -translate-y-1/2 w-6 h-6 z-10"
            />
            <a-input
              id="userId"
              v-model:value="formState.userId"
              placeholder="请输入学号或工号"
              class="w-full px-10 py-2 placeholder-gray-500 border rounded-md focus:outline-none focus:border-blue-500"
            />
          </div>
        </a-form-item>

        <a-form-item name="password">
          <label for="password" class="block text-gray-700 font-medium mb-1">密码</label>
          <div class="relative">
            <img
              src="@/assets/yaoshi.png"
              alt="Password Icon"
              class="absolute left-3 top-[50%] transform -translate-y-1/2 w-6 h-6 z-10"
            />
            <a-input-password
              id="password"
              v-model:value="formState.password"
              placeholder="请输入密码"
              class="w-full px-10 py-2 placeholder-gray-500 border rounded-md focus:outline-none focus:border-blue-500"
            />
          </div>
        </a-form-item>

        <a-form-item name="isTeacher">
          <a-checkbox v-model:checked="formState.isTeacher" class="mr-2" />
          <span class="text-gray-700">教师</span>
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            class="w-full px-4 py-1 bg-blue-500 text-white rounded-md hover:bg-blue-600 focus:outline-none focus:bg-blue-600"
          >
            登录
          </a-button>
        </a-form-item>

        <div class="text-center">
          <a href="javascript:;" @click="goToRegister" class="text-blue-500 hover:underline"
            >还未注册？点击注册</a
          >
        </div>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { message } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { useRouter } from 'vue-router';
import UserDao from '@/daos/user_dao';
import { useStore } from 'vuex';

const formRef = ref();
const router = useRouter();
const userDao = new UserDao();
const store = useStore();

interface FormState {
  userId: string;
  password: string;
  isTeacher: boolean;
}

const formState = reactive<FormState>({
  userId: '',
  password: '',
  isTeacher: false
});

const rules: Record<string, Rule[]> = {
  userId: [{ required: true, message: '请输入学号或工号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
};

const handleLogin = async () => {
  await formRef.value.validate();

  // 2. 确保数字类型转换
  const payload = {
    userId: Number(formState.userId),
    password: formState.password,
    role: formState.isTeacher ? 'teacher' : 'student'
  };
  console.log('登录信息:', payload);

  return userDao
    .findUserByPassword(payload.userId, payload.password, payload.role)
    .then((response) => {
      if (response.data.code === 200) {
        message.success('登录成功！');
        store.dispatch('user/loginSuccess', response.data.data);
        router.push('/');
      } else {
        message.error(response.data.message || '登录失败');
      }
    })
    .catch((error) => {
      console.error('登录错误:', error);
      message.error(error.message || '登录过程中发生错误');
    });
};

const goToRegister = () => {
  router.push({ name: 'Register' });
};
</script>

<style scoped>
/* 保留原有样式 */
</style>
